<?php

    class ManagerController extends AdminController
    {   
        public function init(){
            parent::init();
            $this->menu_parent_selected = 'manager';

        }

        public function filters()
        {
            return array(
                'accessControl', // perform access control for CRUD operations
                'postOnly + delete', // we only allow deletion via POST request
            );
        }

        /**
        * Specifies the access control rules.
        * This method is used by the 'accessControl' filter.
        * @return array access control rules
        */
        public function accessRules()
        {
            return array(
                array('allow',
                    'actions'=>array('login', 'logout'),
                    'users'=>array('*'),
                ),
                array('allow',
                    'actions'=>array('index', 'create'),
                    'users'=>array('@'),
                    'expression' =>  '$user->manager->isManager',
                ),
                array('allow',
                    'actions'=>array('update'),
                    'users'=>array('@'),
                    'expression' =>  array($this, 'ruleCheckUpdate'),
                ),
                array('allow',
                    'actions'=>array('index', 'delete'),
                    'users'=>array('@'),
                    'expression' =>  array($this, 'ruleCheckDelete'),
                ),
                array('deny',
                    'users'=>array('*'),
                ),
            );
        }    

        public function ruleCheckUpdate($user){
            $id = Yii::app()->request->getQuery('id');
            if($id){
                $manager = Manager::model()->findByAttributes(array('id' => $id));
                if(!$manager) return FALSE;

                if($user->manager->isStaffOnly){
                    if($user->manager->id != $manager->id) return FALSE;
                }

                if($user->manager->isManagerOnly){
                    if($manager->isManager && $manager->id != $user->manager->id) return FALSE;
                }
            }
            return TRUE;
        }

        public function ruleCheckDelete($user){
            $id = Yii::app()->request->getQuery('id');

            $manager = Manager::model()->findByAttributes(array('id' => $id));
            if(!$manager || $manager->isAdmin || $user->manager->isStaffOnly) return FALSE;

            if($user->manager->isManagerOnly){
                if($manager->isManager) return FALSE;
            }

            if($user->manager->isAdmin){
                if($manager->isAdmin) return FALSE;
            }

            return TRUE;
        }


        public function actionIndex()
        {
            $this->menu_child_selected = 'manager';
            $this->menu_sub_selected = 'index';

            $model = new Manager('search');
            $model->unsetAttributes();  // clear any default values
            if(isset($_GET['Manager'])) $model->attributes=$_GET['Manager'];

            $this->render('index', array(
                    'model' => $model
                ));
        }

        public function actionCreate()
        {
            $this->menu_child_selected = 'manager_create';
            $this->menu_sub_selected = 'create';

            $model = new Manager('create');
            if(isset($_POST['Manager'])) {
                $model->attributes = Yii::app()->request->getPost('Manager');

                if($model->validate()) {
                    $model->password = $model->getHashPassword($model->password);
                    $model->setIsNewRecord(TRUE);
                    $model->insert();
                    Yii::app()->user->setFlash('success', 'Thêm nhân viên thành công.');
                    $this->refresh();
                }
            }

            $this->render('create', array(
                    'model' => $model
                ));
        }


        public function actionUpdate($id = NULL)
        {
            $this->menu_child_selected = null;
            $this->menu_sub_selected = 'update';

            $model = $id ? $this->loadModel($id) : $this->manager;
            $oldPassword = $model->password;
            if(isset($_POST['Manager'])) {
                $model->attributes = Yii::app()->request->getPost('Manager');

                if($model->validate()) {
                    $model->password = $model->password ? $model->getHashPassword($model->password) : $oldPassword;
                    $model->setIsNewRecord(FALSE);
                    $model->update();
                    Yii::app()->user->setFlash('success', 'Chỉnh sửa nhân viên thành công.');
                    $this->refresh();
                }
            }
            $model->password = null;
            $this->render('update', array(
                    'model' => $model
                ));
        }


        public function actionDelete($id) {
            $manager = $this->loadModel($id);
            $manager->delete();   

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if(!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
        }

        private function loadModel($id) {
            $model = Manager::model()->findByPk($id);
            if($model === null)
                throw new CHttpException(404,'The requested page does not exist.');
            return $model;
        }


        public function actionLogin()
        {
            //        echo '<pre>';print_r(Manager::model()->getHashPassword('1'));echo '</pre>';die;
            if(!Yii::app()->user->isGuest) $this->redirect(array('/admin', 'alias' => $alias));
            $this->layout = '//layouts/blank';

            if(isset($_POST['username']))
            {    
                $identity = new AdminUserIdentity($_POST['username'], $_POST['password']);
                if($identity->authenticate()){
                    Yii::app()->user->login($identity, 3600*24*365);
                    Yii::app()->request->redirect(Yii::app()->user->returnUrl);
                }
                Yii::app()->user->setFlash('error', $identity->errorMessage);

            }

            $this->pageTitle = 'Đăng nhập';
            $this->render('login');
        }

        public function actionLogout()
        {
            Yii::app()->user->logout(false);
            $this->redirect(array('/admin'));
        }
}